#include <stdio.h>
#include <stdlib.h>

int *getdaytab(int leapyear);
int *getdaytab(int leapyear)
{
  static int *daytab[2];
  daytab[0]=malloc(sizeof(int)*13);
  daytab[1]=malloc(sizeof(int)*13);
  *(daytab[0])=0;
  *(daytab[0]+1)=31;          
  *(daytab[0]+2)=28;
  *(daytab[0]+3)=31;
  *(daytab[0]+4)=30;
  *(daytab[0]+5)=31;
  *(daytab[0]+6)=30;
  *(daytab[0]+7)=31;
  *(daytab[0]+8)=31;
  *(daytab[0]+9)=30;
  *(daytab[0]+10)=31;
  *(daytab[0]+11)=30;
  *(daytab[0]+12)=31;
  *(daytab[1])=0;
  *(daytab[1]+1)=31;          
  *(daytab[1]+2)=29;
  *(daytab[1]+3)=31;
  *(daytab[1]+4)=30;
  *(daytab[1]+5)=31;
  *(daytab[1]+6)=30;
  *(daytab[1]+7)=31;
  *(daytab[1]+8)=31;
  *(daytab[1]+9)=30;
  *(daytab[1]+10)=31;
  *(daytab[1]+11)=30;
  *(daytab[1]+12)=31;
  return  (leapyear==1) ? daytab[1] : daytab[0];
}

/* month_day:  set month, day from day of year */
int month_day(int year, int yearday, int *pmonth, int *pday)
{


     int leap=0;

      /* month_day:  set month, day from day of year */
     int i;
     if (year<0) return -16;
     if (yearday>366) return -1;
     if (yearday<1) return -2;
     leap = ((year%4) == 0) && ((year%100) != 0) || ((year%400) == 0);  
     if ((!leap) && (yearday==366)) return -4;
       
     for (i = 1; yearday > *(getdaytab(leap)+i); i++)
       yearday -= *(getdaytab(leap)+i);
       
      *pmonth = i;
      *pday = yearday;
      return 0;
      
}


int day_of_year(int year, int month, int day);
   /* day_of_year:  set day of year from month & day */
   int day_of_year(int year, int month, int day)
   {
       int i, leap;
       
       if (month<1)
         return -1;
       if (month>12)
         return -2;

       leap = ((year%4) == 0) && ((year%100) != 0) || ((year%400) == 0);

       if (day > *(getdaytab(leap)+month))
         return -4;
       if (day <0)
         return -8;
       if(year<0)
         return -16;
       
       for (i = 1; i < month; i++)
         day += *(getdaytab(leap)+i);
       return day;
   }

int main()
{
  int pday = 0;
  int pmonth = 0;  
  //month_day(2017, 365, &pmonth, &pday);
  //  printf ("pday : %d pmonth : %d  \n", pday, pmonth);

  printf("%d \n", day_of_year(2019, 12, 31));

  return (0);
}
